const User = require('../models/User');
const jwt = require('jsonwebtoken');
const { validationResult } = require('express-validator');
const nodemailer = require('nodemailer');

// 生成JWT token
const generateToken = (userId) => {
  return jwt.sign({ id: userId }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN || '7d' // 默认7天
  });
};

// 账号密码登录
exports.login = async (req, res) => {
  try {
    const { account, password } = req.body;

    // 查找用户（支持手机号、邮箱或用户名登录）
    const user = await User.findOne({
      $or: [
        { phone: account },
        { email: account },
        { username: account }
      ]
    });

    if (!user) {
      return res.status(401).json({ message: '账号或密码错误' });
    }

    // 验证密码
    const isMatch = await user.comparePassword(password);
    if (!isMatch) {
      return res.status(401).json({ message: '账号或密码错误' });
    }

    // 生成token
    const token = generateToken(user._id);

    res.json({
      token,
      user: {
        id: user._id,
        phone: user.phone,
        email: user.email,
        username: user.username,
        avatar: user.avatar,
        role: user.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
};

// 手机验证码登录
exports.phoneLogin = async (req, res) => {
  try {
    const { phone, code } = req.body;

    // 验证手机号和验证码
    const user = await User.findOne({ phone });
    if (!user) {
      return res.status(401).json({ message: '手机号未注册' });
    }

    if (!user.verificationCode || 
        user.verificationCode.code !== code || 
        user.verificationCode.expiresAt < new Date()) {
      return res.status(401).json({ message: '验证码无效或已过期' });
    }

    // 清除验证码
    user.verificationCode = undefined;
    await user.save();

    // 生成token
    const token = generateToken(user._id);

    res.json({
      token,
      user: {
        id: user._id,
        phone: user.phone,
        email: user.email,
        username: user.username,
        avatar: user.avatar,
        role: user.role
      }
    });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
};

// 发送验证码
exports.sendVerificationCode = async (req, res) => {
  try {
    const { phone } = req.body;

    // 生成6位随机验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10分钟有效期

    // 查找或创建用户
    let user = await User.findOne({ phone });
    if (!user) {
      user = new User({ phone, password: 'temp_password' });
    }

    // 保存验证码
    user.verificationCode = {
      code,
      expiresAt
    };
    await user.save();

    // TODO: 调用短信服务发送验证码
    console.log(`验证码: ${code}`);

    res.json({ message: '验证码已发送' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
};

// 注册
exports.register = async (req, res) => {
  try {
    const { phone, code, password } = req.body;

    // 查找用户
    let user = await User.findOne({ phone });

    if (!user) {
      return res.status(400).json({ message: '请先获取验证码' });
    }

    if (!user.verificationCode ||
        user.verificationCode.code !== code ||
        user.verificationCode.expiresAt < new Date()) {
      return res.status(401).json({ message: '验证码无效或已过期' });
    }

    if (user.isVerified) {
      return res.status(400).json({ message: '该手机号已注册' });
    }

    // 设置密码并激活用户
    user.password = password;
    user.isVerified = true;
    user.verificationCode = undefined;
    await user.save();

    // 生成token
    const token = generateToken(user._id);

    res.status(201).json({
      token,
      user: {
        id: user._id,
        phone: user.phone,
        role: user.role
      }
    });
  } catch (error) {
    console.error('注册接口错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 忘记密码
exports.forgotPassword = async (req, res) => {
  try {
    const { phone } = req.body;

    const user = await User.findOne({ phone });
    if (!user) {
      return res.status(404).json({ message: '用户不存在' });
    }

    // 生成重置密码token
    const resetToken = jwt.sign(
      { id: user._id },
      process.env.JWT_SECRET,
      { expiresIn: '1h' }
    );

    user.resetPasswordToken = resetToken;
    user.resetPasswordExpires = Date.now() + 3600000; // 1小时
    await user.save();

    // TODO: 发送重置密码链接到用户手机或邮箱

    res.json({ message: '重置密码链接已发送' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
};

// 重置密码
exports.resetPassword = async (req, res) => {
  try {
    const { token, newPassword } = req.body;

    const user = await User.findOne({
      resetPasswordToken: token,
      resetPasswordExpires: { $gt: Date.now() }
    });

    if (!user) {
      return res.status(400).json({ message: '重置密码链接无效或已过期' });
    }

    user.password = newPassword;
    user.resetPasswordToken = undefined;
    user.resetPasswordExpires = undefined;
    await user.save();

    res.json({ message: '密码重置成功' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
};

// 刷新token
exports.refreshToken = async (req, res) => {
  // 你可以根据实际需求实现，这里先返回未实现
  res.status(501).json({ message: '未实现' });
}; 